package net.chrisrichardson.ec2deployer.core

import groovy.mock.interceptor.MockFor

class SshTest extends GroovyTestCase {

    private Ssh ssh
    private final String EXPECTED_SSH_OPTIONS = "-o BatchMode=yes -o StrictHostKeyChecking=no"
    MockFor mockProcessExecutor
    MockFor mockProcessMonitor

    @Override
    protected void setUp() {
        super.setUp();
        Properties properties = new Properties()
        properties.put("sshDir", "ssh-directory")
        properties.put("keyPairFile", "key-pair-file")
        def awsProperties = new AWSProperties(properties)
        ssh = new Ssh(awsProperties)
        mockProcessExecutor = new MockFor(ProcessExecutor.class)
        mockProcessMonitor = new MockFor(ProcessMonitor)
    }


    public void testSsh() {

        def aProcessMonitor

        mockProcessExecutor.demand.execute {cmd, input, processMonitor ->
            assertEquals "ssh-directory/ssh $EXPECTED_SSH_OPTIONS -i key-pair-file  root@foo.com ls", cmd
            assertEquals "input-string", input
            assertEquals "unexpected process monitor", aProcessMonitor, processMonitor    // TODO IllegalAccessException on failNotEquals
            return 0
        }
        mockProcessMonitor.use {
            aProcessMonitor = new SarMonitor() // FIXME - we need a real processMonitor here that matches the mockProcessMonitor
            mockProcessExecutor.use {
                ssh.ssh("foo.com", "ls", "input-string", aProcessMonitor);
            }
        }
    }

    public void testScpUp() {
        mockProcessExecutor.demand.execute {cmd, input, monitor ->
            assertNull input
            assertNull monitor
            assertEquals "ssh-directory/scp $EXPECTED_SSH_OPTIONS -i key-pair-file from-file root@foo.com:to-file", cmd
            return 0
        }
        mockProcessExecutor.use {
            ssh.scpUp("foo.com", "from-file", "to-file");
        }
    }

    public void testScpDown() {
        mockProcessExecutor.demand.execute {cmd, input, monitor ->
            assertNull input
            assertNull monitor
            assertEquals "ssh-directory/scp $EXPECTED_SSH_OPTIONS -i key-pair-file root@foo.com:from-file to-file", cmd
            return 0
        }
        mockProcessExecutor.use {
            ssh.scpDown("foo.com", "from-file", "to-file");
        }
    }

    public void testWaitForSsh() {
        def mockSocket = new MockFor(Socket)
        mockSocket.demand.connect{ where, timeout -> throw new IOException()}
        mockSocket.demand.close {}
        mockSocket.demand.connect{ where, timeout -> }
        mockSocket.demand.close {}

        mockSocket.use {
            ssh.waitUntilSshAvailable("127.0.0.2")
        }
    }

}